package com.atguigu.day4;

import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

class myThread1 implements Runnable {

    @Override
    public void run() {
        System.out.println("实现Runnable的run()");
    }
}

class myCallable implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        System.out.println("Callable=======>come in");
//        TimeUnit.SECONDS.sleep(3);
        return 1024;
    }
}


public class CallableDemo {

    /*
     * 在主线程中需要执行比较耗时的操作时，但又不想阻塞主线程，可以把这些作业交给FutureTask对象在后台完成
     * 当主线程将来需要时，就可以通过FutureTask对象获得后台作业的计算结果或者执行状态
     * */
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        myThread1 myThread1 = new myThread1();
//        myThread1.run();
//        myCallable myCallable = new myCallable();
//        FutureTask<Integer> integerFutureTask = new FutureTask<Integer>(myCallable);
//        new Thread(integerFutureTask,"Callable").start();
//        Integer i = integerFutureTask.get();
//        System.out.println(i);

        //lambda版
        FutureTask<String> stringFutureTask = new FutureTask<>(() -> {
            return "Lambda--->Callable";
        });
        new Thread(stringFutureTask, "l").start();
        System.out.println(stringFutureTask.get());

        FutureTask<Integer> integerFutureTask = new FutureTask<>(new myCallable());
        FutureTask<Integer> integerFutureTask2 = new FutureTask<>(new myCallable());

        new Thread(new FutureTask<Integer>(() -> {
            return 1024;
        })).start();

        new Thread(integerFutureTask, "t1").start();
        new Thread(integerFutureTask2, "t2").start();
        System.out.println(Thread.currentThread().getName() + "-----》 End");
        System.out.println(integerFutureTask.get());
        System.out.println(integerFutureTask.get());
        //FutureTask仅在计算完成时才能检索结果：如果计算尚未完成，则阻塞get方法。一旦计算完成，
        //就不能再重新开始或取消计算。get方法只有在计算完才能获取结果，否则会一直阻塞直到任务转入完成状态，然后会返回结果或者抛出异常
    }
}
